package com.example.easyutils.musicpage;

import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.easyutils.BaseActivity;
import com.example.easyutils.R;
import com.example.easyutils.curstartfortune.StartFortune;
import com.example.easyutils.httputil.HttpGetRequest;
import com.example.easyutils.httputil.HttpPostRequest;
import com.example.easyutils.util.DialogLoad;
import com.example.easyutils.util.MyTypeAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

/*
* https://api.imjad.cn/cloudmusic/?type=playlist&id=1473603590//列表
*
* id: 0: ['云音乐新歌榜', '/discover/toplist?id=3779629'],
    1: ['云音乐热歌榜', '/discover/toplist?id=3778678'],
    2: ['网易原创歌曲榜', '/discover/toplist?id=2884035'],
    3: ['云音乐飙升榜', '/discover/toplist?id=19723756'],
    4: ['云音乐电音榜', '/discover/toplist?id=10520166'],
    5: ['UK排行榜周榜', '/discover/toplist?id=180106'],
    6: ['美国Billboard周榜', '/discover/toplist?id=60198'],
    7: ['KTV嗨榜', '/discover/toplist?id=21845217'],
    8: ['iTunes榜', '/discover/toplist?id=11641012'],
    9: ['Hit FM Top榜', '/discover/toplist?id=120001'],
    10: ['日本Oricon周榜', '/discover/toplist?id=60131'],
    11: ['韩国Melon排行榜周榜', '/discover/toplist?id=3733003'],
    12: ['韩国Mnet排行榜周榜', '/discover/toplist?id=60255'],
    13: ['韩国Melon原声周榜', '/discover/toplist?id=46772709'],
    14: ['中国TOP排行榜(港台榜)', '/discover/toplist?id=112504'],
    15: ['中国TOP排行榜(内地榜)', '/discover/toplist?id=64016'],
    16: ['香港电台中文歌曲龙虎榜', '/discover/toplist?id=10169002'],
    17: ['华语金曲榜', '/discover/toplist?id=4395559'],
    18: ['中国嘻哈榜', '/discover/toplist?id=1899724'],
    19: ['法国 NRJ EuroHot 30周榜', '/discover/toplist?id=27135204'],
    20: ['台湾Hito排行榜', '/discover/toplist?id=112463'],
    21: ['Beatport全球电子舞曲榜', '/discover/toplist?id=3812895']
    *
    *
    * https://api.imjad.cn/cloudmusic/?type=detail&id=1460706496//详细信息
    * https://api.imjad.cn/cloudmusic/?type=details&id=1460706496//播放路径
    *
* */
public class MusicMain extends BaseActivity {
    ZLoadingDialog dialog = new ZLoadingDialog(MusicMain.this);//加载页面动画
    private List songListAll;
    private TextView topTitle;
    private MediaPlayer mediaPlayer = new MediaPlayer();
    private String playUrl,songImage;
    private List dataDetailList;
    private ListView musicListView;
    private static final int GET_MUSIC_LIST_CODE = 1,PLAY_MUSIC_CODE = 2,ERROR_TIME_OUT = 3;
    static String playMusicId = null;
    private List<MusicUtil> endList;
    private Handler handler = new Handler()
    {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case GET_MUSIC_LIST_CODE:
                    Log.d("歌曲列表",dataDetailList+"");
                    endList = new ArrayList<>();
                    for(int i = 0; i < dataDetailList.size(); i ++){

                        String sinner = ((Map)((List)((Map)dataDetailList.get(i)).get("ar")).get(0)).get("name").toString();
                        String songName = ((Map)((Map)dataDetailList.get(i)).get("al")).get("name").toString();
                        String songUrl = ((Map)(((Map)dataDetailList.get(i)).get("al"))).get("picUrl").toString();

                        MusicUtil musicUtil = new MusicUtil(sinner,songName,songUrl);
                        endList.add(musicUtil);
                    }
                    MusicAdapter musicAdapter = new MusicAdapter(MusicMain.this,R.layout.music_item,endList);
                    musicListView.setAdapter(musicAdapter);
                    musicListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            String musicId = ((Map)dataDetailList.get(position)).get("id").toString();
                            String songUrl1 = ((Map)(((Map)dataDetailList.get(position)).get("al"))).get("picUrl").toString();
                            Intent intent = new Intent(MusicMain.this,PlayMusicPage.class);
                            intent.putExtra("musicId",musicId);
                            Log.d("这是id",playMusicId+"---"+musicId);
                            Log.d("这是activity",PlayMusicPage.activity+"");
                            if(PlayMusicPage.activity!=null){
                                if(playMusicId.equals(musicId)){
                                    Log.d("这是id",playMusicId+"--22-"+musicId);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                                }else{
                                    PlayMusicPage.activity.finish();
                                }
                            }

                            startActivity(intent);

                        }
                    });
                    dialog.cancel();
                    break;
                case ERROR_TIME_OUT:
                    Toast.makeText(MusicMain.this,"请求超时",Toast.LENGTH_SHORT).show();
                    dialog.cancel();
                    break;
//                    try {
//                        mediaPlayer.setDataSource(playUrl);
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
            }
        }
    };

//    public abstract class BaseActivity extends AppCompatActivity  {
//
//        @Override
//        protected final void onCreate(Bundle savedInstanceState) {
//            super.onCreate(savedInstanceState);
//            setStatusBar();
//        }
//
//        protected void setStatusBar() {
//            //这里做了两件事情，1.使状态栏透明并使contentView填充到状态栏 2.预留出状态栏的位置，防止界面上的控件离顶部靠的太近。这样就可以实现开头说的第二种情况的沉浸式状态栏了
//            StatusBarUtil.setTransparent(this);
//        }
//    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.music_main);
        Log.d("这是列表页面","test");
        musicListView = (ListView)findViewById(R.id.musicListView);
        topTitle = (TextView)findViewById(R.id.music_top_title);
        Log.d("这是列表页面","test");
        dialog.setLoadingBuilder(Z_TYPE.LEAF_ROTATE)//设置类型
                .setLoadingColor(Color.RED)//颜色
                .setHintText("Loading...")
                .setHintTextSize(16) // 设置字体大小 dp
                .setHintTextColor(Color.GRAY)  // 设置字体颜色
                .setDurationTime(0.5) // 设置动画时间百分比 - 0.5倍
                .setDialogBackgroundColor(Color.parseColor("#CC111111")) // 设置背景色，默认白色
                .show();

        Intent intent = getIntent();
        String activityName = intent.getStringExtra("activityName");
        if(activityName.equals("MusicType")){
            String musicId = intent.getStringExtra("musicId");
            intent.addFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
            getMusicList(musicId);
        }else{
            playMusicId = intent.getStringExtra("playMusicId");
        }

    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d("页面2","不走create");
        Log.d("页面2",intent.getStringExtra("activityName"));
        String activityName = intent.getStringExtra("activityName");
        if(activityName.equals("MusicType")){
            String musicId = intent.getStringExtra("musicId");
            String musicListName = intent.getStringExtra("musicListName");
            topTitle.setText(musicListName);
            getMusicList(musicId);
        }else{
            playMusicId = intent.getStringExtra("playMusicId");
        }
        Log.d("页面3的id",playMusicId+"");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d("返回键",keyCode+"");
        if(keyCode == KeyEvent.KEYCODE_BACK){
            Intent intent = new Intent();
            intent.setClass(MusicMain.this, MusicType.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);//设置不要刷新将要跳到的界面
//            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//它可以关掉所要到的界面中间的activity
            startActivity(intent);
//            finish();

            return true;
        }
        return super.onKeyDown(keyCode, event);

    }

    private void getMusicList(String musicId){
        Log.d("musicId",musicId+"");

        HttpGetRequest.sendOkHttpGetRequst("https://api.imjad.cn/cloudmusic/?type=playlist&id="+musicId,
                new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d("错误",e+"");
                        handler.sendEmptyMessage(ERROR_TIME_OUT);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String dataMap = response.body().string();

                        Gson gson = new GsonBuilder()
                                .registerTypeAdapter(new TypeToken<Map<String, List>>(){

                                }.getType(),new MyTypeAdapter()).create();
                        Map<String,List> dataDetail = gson.fromJson(dataMap,new TypeToken<Map<String,List>>(){

                        }.getType());
                        dataDetailList = new ArrayList<>();
                        dataDetailList = (List) ((Map)dataDetail.get("playlist")).get("tracks");
                        handler.sendEmptyMessage(GET_MUSIC_LIST_CODE);

                        Log.d("成功",((Map)dataDetail.get("playlist")).get("trackIds")+"");
                        List list = new ArrayList();
                        list = (List) ((Map)dataDetail.get("playlist")).get("trackIds");

//                        int randomNum = (int)(1+Math.random()*(list.size()));
                        songListAll = new ArrayList();
                        songListAll = list;
//                        Log.d("list的zhi:",list+"");
//                            getMusicSingle(list);
                    }
                });
    }

    private void playMusic(String id,String songUrl1){
        songImage = songUrl1;
        HttpGetRequest.sendOkHttpGetRequst("https://api.imjad.cn/cloudmusic/?type=details&id="+id,
                new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendEmptyMessage(ERROR_TIME_OUT);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String responseData = response.body().string();
                        Log.d("列表消息",responseData+"");
                        Gson gson = new GsonBuilder()
                                .registerTypeAdapter(new TypeToken<Map<String, List>>(){

                                }.getType(),new MyTypeAdapter()).create();
                        Map<String,List> dataDetail = gson.fromJson(responseData,new TypeToken<Map<String,List>>(){

                        }.getType());
                        playUrl = ((Map)dataDetail.get("data").get(0)).get("url").toString();
                        handler.sendEmptyMessage(PLAY_MUSIC_CODE);

                        Log.d("列表消息11",((Map)dataDetail.get("data").get(0)).get("url")+"");
                    }
                });
    }

    private void getMusicSingle(List list){
        for(int i = 0; i < list.size(); i ++){
            String id = ((Map)list.get(i)).get("id").toString();

            HttpGetRequest.sendOkHttpGetRequst("https://api.imjad.cn/cloudmusic/?type=detail&id="+id,
                    new okhttp3.Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String dataMap = response.body().string();
                            Log.d("成功",dataMap+"");
                            Gson gson = new GsonBuilder()
                                    .registerTypeAdapter(new TypeToken<Map<String, List>>(){

                                    }.getType(),new MyTypeAdapter()).create();
                            Map<String,List> dataDetail = gson.fromJson(dataMap,new TypeToken<Map<String,List>>(){

                            }.getType());
////
                            Log.d("成功",dataDetail+"");
                        }
                    });
        }

    }
}
